var express = require('express');
var router = express.Router();
var model = require('../model/mongodb');
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 注册接口
router.post('/regist', function(req, res, next){
  
  var data = {
    username: req.body.username,
    password: req.body.password,
    password2: req.body.password2
  }
  // 插入数据库之前需要验证数据...
  model.connect(function(db) {
    db.collection('users').insertOne(data, function(err,ret){
      if (err){
        console.log('注册失败')
        res.redirect('/regist')
      }else{
        res.redirect('/login')
      }
    })
  })
})

router.post('/login', function(req, res, next) {
  var data = {
    username: req.body.username,
    password: req.body.password
  }
  // 需要有数据校验
  model.connect(function(db) {
    db.collection('users').find(data).toArray(function(err, docs){ // doc 查询结果
      if (err || docs.length <= 0){
        res.redirect('/login')
      }else{
        // 登录成功
        req.session.username = data.username // 保存到session
        res.redirect('/')
        
      }
    })
  })
})

module.exports = router;
